#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <iostream>
#include <unistd.h>

#include "log.hpp"
class Client
{
public:
    Client(const std::string ServerIp, const uint16_t ServerPort) : _sock(-1), _ServerPort(ServerPort), _ServerIp(ServerIp)
    {}

    void initClient()//创建套接字
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            std::cerr << "socket create error" << std::endl;
            exit(2);
        }
    }
    void start()
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_ServerPort);//??
        server.sin_addr.s_addr = inet_addr(_ServerIp.c_str());

        if(connect(_sock, (struct sockaddr*)&server, sizeof(server)) != 0)
        {
            std::cerr << "socket connect error" << std::endl;
            perror("connect");
        }
        else
        {
            
            //开始聊天
            std::string content;
            while (true)
            {

                //发送消息
                std::cout << "Enter# ";
                std::getline(std::cin, content);
                if(send(_sock,content.c_str(),content.size(),0) < 0)
                {
                    std::cerr << "Failed to msg." << std::endl;
                    return;
                }
                
                logMessage(DEBUG,"send succes fd:%d",_sock);

                //读消息
                char buffer[1024];
                ssize_t len = recv(_sock, buffer, sizeof(buffer), 0);
                buffer[len] = 0;         
                
                logMessage(DEBUG,"recv form server succes:%s",buffer);
            }
        }
        //下线用户
        close(_sock);
    }

private:
    int _sock;
    uint16_t _ServerPort;
    std::string _ServerIp;
};
